/* 登录页思路分析
1.切换登录与注册盒子
2.登录功能
3.注册功能
*/
document.querySelector('.login a').addEventListener('click',function(){
    document.querySelector('.login').style.display = 'none'
    document.querySelector('.register').style.display = 'block'
  })
  document.querySelector('.register a').addEventListener('click',function(){
    document.querySelector('.login').style.display = 'block'
    document.querySelector('.register').style.display = 'none'
  })

  //注册页模块
  document.querySelector('.register .btn').addEventListener('click',function(e){
    e.preventDefault()
    const username = document.querySelector('[name="username"]').value
    const password = document.querySelector('[name="password"]').value
    if(username === '' || password === ''){
      return Toast.fail('账号密码不能为空')
    }
    if(/^\w{6,15}$/.test(username) === false || /^\w{6,15}$/.test(password) === false){
      return Toast.fail('账号密码需包含字母数字,6-15位')
    }
    axios({
      url:'/api/register',
      method:'post',
      data: { username,password},
    }).then(res=>{
      //成功回调
      console.log(res)
      Toast.success(res.data.message)
      if(res.data.code === 0){
        document.querySelector('.register a').click()
      }else{
        Toast.fail(res.data.message)
      }
    })
  })

  //登录页模块
  document.querySelector('.login .btn').addEventListener('click',function(e){
    e.preventDefault()
    const username = document.querySelector('.login [name="username"]').value
    const password = document.querySelector('.login [name="password"]').value
    console.log(username)
    console.log(password)
    if(username === '' || password === ''){
      return Toast.fail('账号密码不能为空')
    }
    if(!/^\w{6,15}$/.test(username) || !/^\w{6,15}$/.test(password)){
      return Toast.fail('账号密码需包含字母数字,6-15位')
    }
    axios({
      url:'/api/login',
      method:'post',
      data: { username,password},
    }).then(res=>{
      //成功回调
      console.log(res)
      Toast.success(res.data.message)
      if(res.data.code === 0){
        localStorage.setItem('token',res.data.token)
        Toast.success(res.data.message)
        location.href = './index.html'
      }else{
        Toast.fail(res.data.message)
      }
    })
  })



